package com.seed.uaa.util;

import cn.hutool.core.date.DateUtil;
import com.seed.core.pojo.Node;
import com.seed.fileud.pojo.FileVO;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class FileKit {
    public static List<Node> getDirectories(String path, String root) {
        List<Node> ret = new ArrayList<>();
        File dir = new File(path);
        if(!dir.isDirectory()) return ret;

        File[] files = dir.listFiles();
        if(files == null) return ret;

        for(File file: files) {
            if(!file.isDirectory()) continue;
            String absPath = file.getAbsolutePath();
            Node node = new Node();
            node.setLabel(file.getName());
            node.setValue(absPath.substring(root.length()));

            List<Node> children = getDirectories(absPath, root);
            if(!children.isEmpty()) node.setChildren(children);

            ret.add(node);
        }

        return ret;
    }

    public static List<FileVO> getFiles(String path, String root) {
        if(!root.endsWith("/")) root = root + '/';
        List<FileVO> ret = new ArrayList<>();
        File dir = new File(root + path);
        if(!dir.isDirectory()) return ret;

        File[] files = dir.listFiles();
        if(files == null) return ret;

        for(File file: files) {
            if(file.isDirectory()) continue;

            FileVO vo = new FileVO();
            vo.setName(file.getName());
            vo.setSize(file.length());
            vo.setLastModified(DateUtil.format(new Date(file.lastModified()), "yyyy-MM-dd HH:mm:ss"));
            ret.add(vo);
        }

        return ret;
    }
}
